﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockCommon.data;
using System.IO;
using StockCommon;
using StockCommon.baseclass;
using StockImport.dataimport.common;
using Utilities;
using System.Text.RegularExpressions;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data;
using StockCommon.Calendar;
using StockCommon.TaskLog;

namespace StockImport.dataimport.otc.sb
{
    public class OTC_SB_Import : SB_Import_Common
    {
        protected Guid? taskId = null;

        protected  override Guid getObjectId()
        {
            if(taskId==null)
                taskId = ObjectExecServices.getServicesId("dateimport", "上櫃_券商買賣證券日報表", "1.0");
            return (Guid)taskId;
        }
        protected override TwnStockMarketType getMarket()
        {
            return TwnStockMarketType.上櫃;
        }
        protected override void createLog(DateTime date)
        {
            //TODO~~
            TwnStockMarketType market=getMarket();
        }

        protected override String getStorePath(DateTime date)
        {
            String r = String.Format(@"D:\SBData\tempotc\{0}", DateUtils.toShortDateFormat_NoSlash(date));
            return r;
        }

        public override bool hasSourceData(DateTime date)
        {
            String pa = getStorePath(date);
            if (Directory.Exists(pa))
            {
                String[] fs=Directory.GetFiles(pa);
                if (fs.Length > 600)
                    return true;
            }
            return false;
        }

        protected override int update_internal(DateTime date,bool deleteOld)
        {
            String path = getStorePath(date);
            String[] fs = Directory.GetFiles(path);
            if (fs.Length == 0)
                return 0;
            int c = 0;
            foreach (String fileName in fs)
            {
                String fn = Path.GetFileName(fileName);
                if (fn.EndsWith(".csv") == false)
                    continue;
                if (fn.Contains("utf8"))
                    continue;
                int pos = fn.IndexOf(".");
                String code = fn.Substring(0, pos);
                //因為要有檔案,才會走到這一步,因此deleteOld倒是可以允許的
                if (updateFromFile(fileName, code, date, deleteOld))
                    c++;
            }
            return c;
        }
        /**************************************
         * 
         * *************************************/
        protected override int updateFromFile_internal(string code, DateTime date, string fileName, Guid taskId)
        {
            try
            {
                String content = File.ReadAllText(fileName);

                String pat = "\"([^\"]*)\",\"([^\"]*)\",\"([^\"]*)\",\"([^\"]*)\",\"([^\"]*)\"";
                MatchCollection matches = Regex.Matches(content, pat, RegexOptions.IgnoreCase);
                List<SBDetail> details = new List<SBDetail>();
                foreach (Match match in matches)
                {
                    SBDetail sbdetail = new SBDetail();
                    sbdetail.seq = int.Parse(match.Groups[1].Value);

                    String instcodename = match.Groups[2].Value.Trim();
                    String[] ss = instcodename.Split(' ');
                    Guid instId = Guid.NewGuid();
                    if (TradeInstManager.getInstId(ss[0], ref  instId))
                    {
                        sbdetail.instId = instId;
                    }
                    else
                    {
                        //因為最後一段一定是..
                        sbdetail.instId = TradeInstManager.registerInst(ss[0], ss[ss.Length - 1]);
                    }
                    sbdetail.price = decimal.Parse(match.Groups[3].Value);
                    sbdetail.buy = Convert.ToInt32(decimal.Parse(match.Groups[4].Value));
                    sbdetail.sell = Convert.ToInt32(decimal.Parse(match.Groups[5].Value));
                    sbdetail.StockCode = code;
                    sbdetail.日期 = date;
                    details.Add(sbdetail);
                }
                System.Diagnostics.Debug.WriteLine(date.ToShortDateString() + "\t" + code + "\t" + details.Count + "筆");
                if (details.Count == 0)
                    return 0;
                performInsert(code, date, taskId, details);
                int c = details.Count;
                details.Clear();
                return c;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error:" + date.ToShortDateString() + "\t" + code);
                return -1;
            }
        }


        //乃是csv big5編碼


    }
}
